package main

import (
	"fmt"
	"gorm-study/src/pkg/student/models"
	"gorm-study/src/pkg/utils/dbutil"
)

func main() {
	CreateStudents()

	var students []models.Student
	dbutil.DB.Find(&students)
	for _, student := range students {
		fmt.Printf("ID: %v, Name:%v \n", student.ID, student.Name)
	}
}

func CreateStudents() error {
	tx := dbutil.DB.Begin()
	defer func() {
		if err := recover(); err != nil {
			tx.Rollback() // 捕获任何错误都需要手动 rollbak
		}
	}()

	if err := tx.Error; err != nil {
		tx.Rollback() // 每个出现 err 的地方都要手动 rollback
		return err
	}

	if err := tx.Create(&models.Student{Name: "熊大"}).Error; err != nil {
		tx.Rollback()
		return err
	}

	xionger := models.Student{}
	xionger.ID = 2
	xionger.Name = "熊二"
	if err := tx.Create(&xionger).Error; err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error // 最终需要手动提交
}
